<template>
  <div class="list">
    <el-card class="box-card">
      <div class="body">
        <el-row>
          <el-col :span="4">
            <el-tree
              :data="treeData"
              node-key="id"
              :props="defaultProps"
              :default-expand-all="true"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            ></el-tree>
          </el-col>
          <el-col :span="20">
            <el-row>
              <!-- <div slot="header" class="clearfix"> -->
              <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
              >
                <el-form-item label="关键字">
                  <el-input
                    clearable
                    v-model="searchForm.keyword"
                    placeholder="请输入关键字"
                  ></el-input>
                </el-form-item>
                <!-- <el-form-item label="所属部门">
                  <el-select
                    v-model="searchForm.deptId"
                    clearable
                    placeholder="请选择你的部门"
                  >
                    <el-option
                      v-for="item in departmentInfo"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item> -->
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">查询</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button
                    round
                    class="el-icon-refresh-right"
                    @click="handleRefresh()"
                    >刷新</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button type="success" @click="handleAddForm"
                    >新增</el-button
                  >
                </el-form-item>
              </el-form>
              <!-- </div> -->
            </el-row>
            <el-row>
              <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="id" label="编号" width="50" />
                <el-table-column prop="avatar" label="头像" width="60">
                  <template slot-scope="scope">
                    <el-tooltip
                      class="tooltipItem"
                      effect="dark"
                      content="点击更换头像 "
                      placement="bottom"
                    >
                      <el-avatar
                        :size="50"
                        @click.native="handleChangeAvatar(scope.row)"
                        :src="
                          scope.row.avatar ? scope.row.avatar : defaultAvatar
                        "
                      ></el-avatar>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="username" label="姓名" width="80" />
                <el-table-column prop="name" label="昵称" width="150" />
                <el-table-column prop="age" label="年龄" width="100" />
                <el-table-column prop="admin" label="管理员" width="180">
                  <template v-slot="scope">
                    <el-tag
                      effect="plain"
                      disable-transitions
                      :type="scope.row.admin ? 'warning' : 'success'"
                      >{{ scope.row.admin | formatterFilter }}</el-tag
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="dept.name" label="所属部门" width="180">
                </el-table-column>
                <el-table-column width="300" fixed="right" label="操作">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="success"
                      class="el-icon-refresh"
                      @click="handleRest(scope.row)"
                      >重置密码</el-button
                    >
                    <el-button
                      size="mini"
                      type="primary"
                      class="el-icon-edit"
                      @click="handleEdit(scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      class="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
            <el-row>
              <el-pagination
                style="text-align: right"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="searchForm.currentPage"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="100"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              >
              </el-pagination>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" status-icon ref="editForm" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input
            type="number"
            v-model.number="editForm.age"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- :inactive-value="false"
            :active-value="true" -->
        <el-form-item label="管理员">
          <el-switch v-model="editForm.admin"></el-switch>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select
            v-model="value"
            placeholder="请选择你的部门"
            @change="changeDepartment(departmentInfo)"
          >
            <el-option
              v-for="item in departmentInfo"
              :key="item.id"
              :label="item.nane"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="40%"
      title=""
      :visible.sync="dialogForm.dialogFormVisible"
    >
      <span slot="label"><i class="el-icon-refresh"></i> 重置密码</span>
      <el-form
        :model="restForm"
        :rules="restFormRules"
        status-icon
        ref="restForm"
        label-width="80px"
      >
        <el-form-item label="原始密码" prop="oldPassword">
          <el-input
            placeholder="请输入原始密码"
            v-model="restForm.oldPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            placeholder="请输入新密码"
            v-model="restForm.newPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="surePassword">
          <el-input
            placeholder="请确认密码"
            v-model="restForm.surePassword"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogForm.dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleRestForm('restForm')"
          >确 定</el-button
        >
      </div></el-dialog
    >
  </div>
</template>

<script>
import axios from "axios";
import {
  employeeList,
  saveOrUpdate,
  deleteById,
  restPassword,
} from "@/api/employee";
import { departmentAll, treeList } from "@/api/department";

const getDeptIds = (arr, dept) => {
  arr.push(dept.id);
  if (dept.children) {
    for (let i in dept.children) {
      getDeptIds(arr, dept.children[i]);
    }
  }
};

export default {
  name: "List",
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length >= 6 && this.restForm.newPassword != value) {
        callback(new Error("两次输入的密码不一致，请确认你的密码"));
      } else {
        callback();
      }
    };
    return {
      total: 0,
      value: "",
      dialogTitle: "",
      isSwitch: true,
      dialogFormVisible: false,
      searchForm: {
        keyword: "",
        deptId: undefined,
        currentPage: 1,
        pageSize: 3,
      },
      tableData: [],
      departmentInfo: [],
      editForm: {},
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      defaultAvatar:
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      randomUrl: "",
      dialogForm: {
        name: "2332323",
        dialogFormVisible: false,
      },
      restForm: {
        oldPassword: "",
        newPassword: "",
        surePassword: "",
        id: null,
      },
      restFormRules: {
        oldPassword: [
          { required: true, message: "请填写旧密码", trigger: "blur" },
          { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" },
        ],
        newPassword: [
          { required: true, message: "请输入新的密码", trigger: "blur" },
          { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" },
        ],
        surePassword: [
          {
            required: true,
            validator: validatePassword,
          },
        ],
      },
    };
  },
  methods: {
    fetchData(params) {
      employeeList(params).then((res) => {
        const { data } = res;
        this.total = data.totalCount;
        this.tableData = data.data;
        this.searchForm.currentPage = data.currentPage;
        this.searchForm.pageSize = data.pageSize;
      });
      departmentAll(params).then((res) => {
        this.departmentInfo = res.data;
      });
    },
    onSubmit() {
      this.fetchData(this.searchForm);
    },
    handleEdit(data) {
      this.dialogFormVisible = true;
      this.dialogTitle = "员工编辑";
      this.editForm = data;
      this.value = data.dept.name;
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除这一条记录, 确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deleteById(row.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.fetchData(this.searchForm);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange(currentPage) {
      this.searchForm.currentPage = currentPage;
      this.fetchData(this.searchForm);
    },
    handleSizeChange(pageSize) {
      this.searchForm.pageSize = pageSize;
      this.fetchData(this.searchForm);
    },
    handleAddForm() {
      this.dialogTitle = "员工新增";
      this.resetForm("editForm");
      this.dialogFormVisible = true;
      this.editForm = {};
    },
    handleEditForm() {
      saveOrUpdate(this.editForm).then((res) => {
        this.fetchData(this.searchForm);
        this.$message.success("操作成功！");
        this.dialogFormVisible = false;
      });
    },
    changeDepartment(data) {
      data.forEach((element) => {
        if (element.name === this.value) {
          this.editForm.dept = element;
        }
      });
      console.log(this.editForm);
    },
    handleNodeClick(data) {
      this.searchForm.deptId = data.id;
      this.searchForm.currentPage = 1;

      let deptIds = [];
      getDeptIds(deptIds, data);
      // 重新查询员工信息
      this.searchForm.deptIds = deptIds;
      this.fetchData(this.searchForm);
    },
    /**
     * 异步发送第三方 API 接口，请求生成随机头像并返回
     */
    randomAvatar() {
      const config = {
        method: "get",
        url: "https://api.btstu.cn/sjtx/api.php",
        params: {
          lx: "b1",
          format: "json",
        },
        responseType: "json",
      };
      axios(config)
        .then((res) => {
          console.log("相应内容：", res.data);
          this.randomUrl = res.data.imgurl;
        })
        .catch((err) => {
          console.log("错误异常：", err);
          this.$message.error(err.message);
        });
    },
    handleChangeAvatar(data) {
      this.$confirm("此操作将更换当前头像, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.editForm.avatar = this.editForm = data;
          console.log(data);
          console.log(this.editForm);
          this.randomAvatar();
          // 调用接口生成随机图片
          this.editForm.avatar = this.randomUrl;
          console.log(this.editForm);
          saveOrUpdate(this.editForm).then((res) => {
            this.fetchData(this.searchForm);
            // this.$message.success("头像更换成功！");
          });
          this.$message({
            type: "success",
            message: "更换成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消更换",
          });
        });
    },
    handleRefresh() {
      // location.reload();
      this.resetForm("editForm");
      this.searchForm = {};
      this.fetchData();
    },
    handleRest(row) {
      this.dialogForm.dialogFormVisible = true;
      this.restForm.id = row.id;
      this.resetForm("restForm");
    },
    handleRestForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 重置密码的表单
          restPassword(this.restForm).then((res) => {
            if (res.code === 200) {
              this.$message.success("员工密码修改成功！");
              this.dialogForm.dialogFormVisible = false;
              // 清空表单并重置校验状态
              this.restForm = {
                oldPassword: "",
                newPassword: "",
                surePassword: "",
                id: null,
              };
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  filters: {
    formatterFilter(isAdmin) {
      return isAdmin ? "管理员" : "普通用户";
    },
  },
  mounted() {
    this.fetchData();
    treeList().then((res) => {
      this.treeData = res.data;
    });
  },
};
</script>

<style scoped>
.el-avatar:hover {
  cursor: pointer;
}
</style>